package com.woniu.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.woniu.entity.Result;
import com.woniu.entity.ResultCode;
import com.woniu.user.enity.dto.OperationLoginDTO;
import com.woniu.user.pojo.Operation;
import com.woniu.user.service.IOperationService;
import com.woniu.user.util.AesUtil;
import com.woniu.user.util.SMSUtils;
import com.woniu.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;


import org.springframework.web.bind.annotation.*;


import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 运营端用户表 前端控制器
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Api(tags = "运营端用户登录")
@Slf4j
@RestController
@RequestMapping("/operation")
public class OperationController {

    @Autowired
    private IOperationService operationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("查询所有用户")
    @GetMapping("/findAll")
    public Result<List<Operation>> queryAll(){
        List<Operation> operationList = operationService.list();
        return Result.ok(operationList);
    }


    @GetMapping("/sendCode/{phone}")
    @ApiOperation("发送短信验证码")
    public Result<Operation> sendSmsCode(@PathVariable String phone) {
        //校验手机号正则表达式
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(16[5,6])|(17[0-8])|(18[0-9])|(19[1、5、8、9]))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        boolean flag = matcher.matches();
        if(!flag){
            return Result.error(401,"手机号格式错误！");
        }

        // 校验手机号码是否存在
        QueryWrapper<Operation> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        Operation one = operationService.getOne(wrapper);
        if (one != null) {
            return Result.error(401,"手机号已存在");
        }

        //查看是否有没过期的验证码
        String code1 = stringRedisTemplate.opsForValue().get("REGIST_CODE_" + phone);
        if (code1 != null) { // 说明存在
            return Result.error(401,"验证码已发送，请勿重复发送");
        }
        // 随机生成4位验证吗
        Random randObj = new Random();
        String code = Integer.toString(1000 + randObj.nextInt(9000));
        log.info("======验证码为" + code + "======");
        // 将验证码保存到Redis中
        stringRedisTemplate.opsForValue().set("REGIST_CODE_" + phone, code, 60 * 5, TimeUnit.SECONDS);
        // 发送短信
        SMSUtils.sendSms(phone,code);
        return Result.ok();
    }

    @ApiOperation("验证短信验证码+注册")
    @PostMapping("/check/{phone}/{code}/{password}")
    public Result<String> checkCode(@PathVariable String phone, @PathVariable String code, @PathVariable String password) {
        String redisCode = stringRedisTemplate.opsForValue().get("REGIST_CODE_" + phone);
        log.debug("======验证码为" + redisCode + "======");
        if (redisCode != null && redisCode.length() > 0) {
            if (redisCode.equals(code)) {
                log.debug("========短信验证成功=======");
                stringRedisTemplate.delete("REGIST_CODE_" + phone);
                // 封装operation
                Operation operation = new Operation();
                operation.setPhone(phone);
                String encrypt = AesUtil.encrypt(password);
                operation.setPassword(encrypt);
                operationService.save(operation);
                return Result.ok();
            }
        }
        return Result.error("手机号或验证码错误");
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody OperationLoginDTO operationLoginDTO) {

        Operation operation = operationService.operationLogin(operationLoginDTO);
        if(operation == null){// 登录失败，用户名或者密码错误
            return Result.error(ResultCode.USER_LOGIN_ERROR.getCode(), ResultCode.USER_LOGIN_ERROR.getMessage());
        }
        // 登录成功，生成token，并且将token存放到Redis中
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", operationLoginDTO.getUsername());
        String token  = JwtUtil.createJWT(UUID.randomUUID().toString(), claims);
        // 将token存储到Redis中
        stringRedisTemplate.opsForValue().set("token_" + token, token, 60 * 30L, TimeUnit.SECONDS);
        // 登录成功，构建返回的数据
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", token);
        return Result.ok(map);
    }

}
